package com.newtouch.bxzs.database.service.impl;

import com.google.common.collect.Lists;
import com.newtouch.bxzs.database.mapper.ButtonMapper;
import com.newtouch.bxzs.database.mapper.MenuMapper;
import com.newtouch.bxzs.database.model.bo.MenuButtonBO;
import com.newtouch.bxzs.database.model.bo.MenuTreeBO;
import com.newtouch.bxzs.database.service.MenuService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 菜单Service实现类:
 *
 * <p>
 * <b>History:</b>
 * <table border="1">
 * <tr>
 * <th>Date</th>
 * <th>Operator</th>
 * <th>Memo</th>
 * </tr>
 * <tr>
 * <td>2021/1/5 10:29</td>
 * <td>zhangqianyang</td>
 * <td>Create</td>
 * </tr>
 * </table>
 *
 * @author zhangqianyang
 * @version 1.0.0
 * @since 1.0.0
 */
@Service
public class MenuServiceImpl implements MenuService {
    @Resource
    private ButtonMapper buttonMapper;

    @Resource
    private MenuMapper menuMapper;

    /**
     * 获取菜单树
     * @param terminalType 终端类型
     * @return List<MenuTreeBO>
     */
    @Override
    public List<MenuTreeBO> getMenuList(String terminalType) {
        // 查出全部菜单集合
        List<MenuTreeBO> menuList = menuMapper.listAllMenu(terminalType);
        List<MenuTreeBO> results = Lists.newArrayList();
        for (MenuTreeBO menu : menuList) {
            if ("".equals(menu.getParentMenuId()) || null == menu.getParentMenuId()) {
                results.add(recursion(menuList, menu));
            }
        }
        return results;
    }


    /**
     * 获取选中菜单的按钮列表
     * * @param menuIdList 菜单id
     *
     * @return List<MenuButtonBO>
     */
    @Override
    public List<MenuButtonBO> getMenuButtonList(List<String> menuIdList) {
        if(menuIdList == null || menuIdList.isEmpty()){
            return new ArrayList<>();
        }
        return buttonMapper.listButtonsByMenuId(menuIdList);
    }

    /**
     * 递归处理子级菜单
     *
     * @param list       菜单列表
     * @param menuTreeBO 父级菜单
     * @return MenuTreeBO
     */
    private MenuTreeBO recursion(List<MenuTreeBO> list, MenuTreeBO menuTreeBO) {
        MenuTreeBO result = new MenuTreeBO();
        result.setMenuId(menuTreeBO.getMenuId());
        result.setMenuName(menuTreeBO.getMenuName());
        result.setParentMenuId(menuTreeBO.getParentMenuId());
        for (MenuTreeBO menu : list) {
            if (Objects.equals(menu.getParentMenuId(), menuTreeBO.getMenuId())) {
                if (result.getChildren() == null) {
                    result.setChildren(Lists.newArrayList());
                }
                result.getChildren().add(recursion(list, menu));
            }
        }
        return result;
    }
}
